//
//  ButtonDetailsViewController.m
//  随便点
//
//  Created by ZC on 15/3/30.
//  Copyright (c) 2015年 qfsoft. All rights reserved.
//

#import "ButtonDetailsViewController.h"
#import "ButtonClickCell.h"
#import "StoreList.h"
#import "DetailsViewController.h"
#import "AppDelegate.h"
#import "OrderBuyViewController.h"
#import "BMapKit.h"
#define shousuo @"http://www.51anys.com:8080/waimaiwang/shop/search"   //搜索接口

@interface ButtonDetailsViewController (){
    NSDictionary *dic;
    NSMutableArray *array;
    NSMutableArray *ssarray;
    NSMutableArray *StoreListArray;
    AppDelegate *B1delegate;
    NSString *str1;
    NSString *str2;
    NSString *str3;
    BMKLocationService * _locService;
    NSDictionary *sousuodic;
    NSDictionary *sousuodic1;

}

@property (nonatomic,strong)RefreshControl * refreshControl;
@end

@implementation ButtonDetailsViewController

- (void)viewDidLoad {
    self.navigationItem.hidesBackButton = YES;
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed: @"back.png"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = item;
    
    //tableView 顶端不出现空白
    self.automaticallyAdjustsScrollViewInsets=NO;
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    //启动LocationService
    [_locService startUserLocationService];
    B1delegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    array=[NSMutableArray array];
    StoreListArray=[NSMutableArray array];
    
    //默认跳过条数为0
    str2 = @"0";
    if ([self.sstext.text isEqualToString:@""]) {
        //请求数据
        [self setUpNotes];
    }
    self.ssdj.userInteractionEnabled=YES;
    UITapGestureRecognizer *click = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dianji)];
    [self.ssdj addGestureRecognizer:click];
    //上拉刷新
    
//    self.BTableView.dataSource = nil;
    
    _refreshControl=[[RefreshControl alloc] initWithScrollView:self.BTableView delegate:self];
    _refreshControl.topEnabled=NO;
    _refreshControl.bottomEnabled=YES;
    
    [self.BTableView reloadData];

    [super viewDidLoad];
}
-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)dianji{
    if ([self.sstext.text isEqualToString:@""]) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"请输入关键字" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }else{
        StoreListArray = [NSMutableArray array];
        [self sous];
        
    }
}
-(void)sous{
    _jkurl=[NSURL URLWithString:shousuo];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:_jkurl];
    NSString *postStr=[NSString stringWithFormat:@"keyword=%@&index=%d",self.sstext.text,[str2 intValue]];
    [request setHTTPMethod:@"post"];
    NSData *data=[postStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        sousuodic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData1:) withObject:sousuodic waitUntilDone:YES];
        ssarray  = sousuodic[@"list"];
        for(NSDictionary *obj in ssarray){
            StoreList *storeList=[[StoreList alloc] init];
            storeList.ID=obj[@"id"];
            storeList.StoreImage=obj[@"image"];
            storeList.StoreName=obj[@"name"];
            storeList.Address=obj[@"address"];
            storeList.Salescount=obj[@"count"];
            storeList.Distance=@"";
            storeList.StoreState=obj[@"state"];
            
            [StoreListArray addObject:storeList];
        }
        [self.BTableView reloadData];
    }];
}
-(void)refreshData1:(NSArray *)sender{
    
}
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    _jingdu = userLocation.location.coordinate.latitude;
    _weidu = userLocation.location.coordinate.longitude;
    BMKGeoCodeSearch *search = [[BMKGeoCodeSearch alloc]init];
    search.delegate=self;
    BMKReverseGeoCodeOption *rever = [[BMKReverseGeoCodeOption alloc]init];
    rever.reverseGeoPoint = userLocation.location.coordinate;
    [_locService stopUserLocationService];
}
-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
        self.dqdz.text = result.address;
}
- (void)refreshControl:(RefreshControl *)refreshControl didEngageRefreshDirection:(RefreshDirection)direction
{
    if (direction==RefreshDirectionTop)
    {
        
        [StoreListArray removeAllObjects];
        
    }
    else if (direction==RefreshDirectionBottom)
    {
        
    }
    
    __weak typeof(self)weakSelf=self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        __strong typeof(weakSelf)strongSelf=weakSelf;
        [strongSelf reloadData];
    });
    
}

-(void)reloadData
{
    
    str2=[NSString stringWithFormat:@"%d",[str2 intValue]+10];
    if ([self.sstext.text isEqualToString:@""]) {
        
        [self setUpNotes];
    }else{
        [self sous];
    }
    
    if (self.refreshControl.refreshingDirection==RefreshingDirectionTop)
    {
        [self.refreshControl finishRefreshingDirection:RefreshDirectionTop];
    }
    else if (self.refreshControl.refreshingDirection==RefreshingDirectionBottom)
    {
        [self.refreshControl finishRefreshingDirection:RefreshDirectionBottom];
        
    }
    
    [self.BTableView reloadData];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return StoreListArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UINib *nib = [UINib nibWithNibName:@"ButtonClickCell" bundle:nil];
    [_BTableView registerNib:nib forCellReuseIdentifier:@"BCcell"];
    
    
    static NSString *cellIdentifier=@"BCcell";
    ButtonClickCell *cell=[_BTableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    StoreList *sl=StoreListArray[indexPath.row];
    
    cell.BCName.text = [NSString stringWithFormat:@"%@",sl.StoreName];
    cell.BCAddress.text=[NSString stringWithFormat:@"%@",sl.Address];
    cell.BCCount.text=[NSString stringWithFormat:@"%@",sl.Salescount];
    cell.BCDistance.text=[NSString stringWithFormat:@"%@",sl.Distance];
    B1delegate.ShopName=[NSString stringWithFormat:@"%@",sl.StoreName];
    NSString *haha=@"http://www.51anys.com:8080/waimaiwang/resources/";
    NSString *hehe=[NSString stringWithFormat:@"%@",sl.StoreImage];
    NSString *string=[NSString stringWithFormat:@"%@%@",haha,hehe];
    NSURL *url=[NSURL URLWithString:string];
    cell.BCImage.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
    
    
    
    return cell;
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //把店铺名称和店铺ID传到下一个页面
    StoreList *sl=StoreListArray[indexPath.row];
    B1delegate.spid=[NSString stringWithFormat:@"%@",sl.ID];
    B1delegate.ShopName=[NSString stringWithFormat:@"%@",sl.StoreName];
    
    if (B1delegate.ViewC.ButtonChoose ==1 || B1delegate.ViewC.ButtonChoose ==2 || B1delegate.ViewC.ButtonChoose ==4) {
        
        //直接进入店铺选择商品
        ShopDetailViewController *B1detail=[self.storyboard instantiateViewControllerWithIdentifier:@"DetailsVC"];
        [self.navigationController pushViewController:B1detail animated:YES];
        

    }else{
        
        
        // 跳转到订购页面
        OrderBuyViewController *order=[[OrderBuyViewController alloc]init];
        [self.navigationController pushViewController:order animated:YES];
    }
    


    
}

-(void)setUpNotes{
    NSString *jingdu = @"31.9078120000";
    NSString *weidu = @"120.6272790000";
    
    //“随便点”接口
    if (B1delegate.ViewC.ButtonChoose==1) {
        str1=@"http://www.51anys.com:8080/waimaiwang/shop/shopList/0";
        str3=[NSString stringWithFormat:@"%@/%@",str1,str2];
        self.url=str3;
    }
    //“随便购”接口
    else if (B1delegate.ViewC.ButtonChoose==2) {

        str1=@"http://www.51anys.com:8080/waimaiwang/shop/shopList/2";
        str3=[NSString stringWithFormat:@"%@/%@",str1,str2];
        self.url=str3;
        
    }
    //“随便订”接口
    else{
        str1=@"http://www.51anys.com:8080/waimaiwang/shop/shopList/1";
        str3=[NSString stringWithFormat:@"%@/%@",str1,str2];
        self.url=str3;
    }
    
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url]];
    NSString *postStr=[NSString stringWithFormat:@"longitude%@latitude%@",jingdu,weidu];
    [request setHTTPMethod:@"post"];
    NSData *data=[postStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData2) withObject:dic waitUntilDone:YES];
        array  = dic[@"list"];
        for(NSDictionary *obj in array){
            StoreList *storeList=[[StoreList alloc] init];
            storeList.ID=obj[@"id"];
            storeList.StoreImage=obj[@"image"];
            storeList.StoreName=obj[@"name"];
            storeList.Address=obj[@"address"];
            storeList.Salescount=obj[@"count"];
            storeList.Distance=obj[@"distance"];
            storeList.StoreState=obj[@"state"];
            
            [StoreListArray addObject:storeList];
        }
        [self.BTableView reloadData];
    }];
    
}

-(void)refreshData2{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
